<template>
  <div class="rules-regulations-management-style">
    <!-- 背景图 -->
    <div
      id="background"
      :style="`background-image: url(${require('@/assets/images/jjxt/ywzt/ywzt-index-background.png')})`"
    />
    <!-- 背景图 -->

    <!-- 顶部导航栏 -->
    <top-navigation-bar active-item="/rule-regulation-management" :is-not-transparent="true" />
    <!-- 顶部导航栏 -->

    <div class="rules-regulations-of-power-supply-style app-container v-flex">
      <div class="title">供电专业规章制度</div>
      <div class="rules-content">
        <div class="app-container__left tree-box">
          <div class="type-title">发文机构</div>
          <ul class="type-list">
            <li
              :class="{ active: listQuery.organization === '' }"
              @click="chooseOrganization({id: ''})"
            >所有机构</li>
            <li
              v-for="(item, index) in organizations"
              :key="index"
              :class="{ active: item.id === listQuery.organization }"
              @click="chooseOrganization(item)"
            >{{ item.dicKey }}</li>
          </ul>
        </div>
        <div class="rules-content-right">
          <!-- 顶部操作栏 -->
          <div class="top-operation">
            <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
          </div>
          <!-- 顶部操作栏 -->

          <!-- 表格 -->
          <div ref="main" class="v-flex-elastic table-style">
            <el-table
              v-if="height>0"
              ref="multipleTable"
              v-loading="listLoading"
              :data="tableData"
              border
              :height="height"
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column label="序号" align="center" type="index" width="50" />
              <el-table-column show-overflow-tooltip label="文件名">
                <template slot-scope="{row}">
                  <span class="view-file" @click="viewFile(row)">{{ row.fileName }}</span>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip prop="subject" label="题名" />
              <el-table-column show-overflow-tooltip prop="keyWords" label="主题词" />
              <el-table-column label="发文日期" width="100" align="center">
                <template slot-scope="{row}">{{ parseTime(row.pubDate, '{y}-{m}-{d}') }}</template>
              </el-table-column>
              <el-table-column show-overflow-tooltip prop="docCode" label="文号" />
              <el-table-column prop="deptName" label="部门" width="180" align="center" />
              <el-table-column label="有效" width="60" align="center">
                <template slot-scope="{row}">{{ row.validFlag ? '是' : '否' }}</template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="100"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="{row ,$index}">
                  <download :params="{url: row.filePath, fileName: row.fileName}">
                    <el-button
                      class="el-icon-defined"
                      style="margin-right:5px;"
                      size="mini"
                      icon="el-icon-download"
                    />
                  </download>
                  <el-button
                    v-permission-button="publicConfig['ITPS-VIEW']"
                    class="el-icon-defined"
                    size="mini"
                    icon="el-icon-view"
                    @click="view(row)"
                  />
                  <el-button
                    v-permission-button="publicConfig['ITPS-UPDATE']"
                    class="el-icon-defined"
                    size="mini"
                    icon="el-icon-edit"
                    @click="updateForm(row,$index)"
                  />
                  <el-button
                    v-permission-button="publicConfig['ITPS-DELETE']"
                    class="el-icon-defined"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteData(row,$index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 表格 -->

          <!-- 分页 -->
          <div class="page-box">
            <pagination
              :total="total"
              :page.sync="listQuery.page"
              :size.sync="listQuery.size"
              @pagination="getListPage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 弹框 -->
    <base-dialog
      class="tech-regulation-dialog"
      width="800px"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @close="beforeCloseDialog"
      @open="beforeOpenDialog"
      @updateData="updateData"
    >
      <div class="h-flex">
        <div class="tech-regulation-dialog__left tree-box">
          <div class="type-title">发文机构</div>
          <ul class="type-list">
            <li
              v-for="(item, index) in organizations"
              :key="index"
              :class="{ active: item.id === dialog.form.organization }"
              @click="$set(dialog.form, 'organization', item.id)"
            >{{ item.dicKey }}</li>
          </ul>
        </div>
        <div class="tech-regulation-dialog__right h-flex-elastic">
          <el-form
            ref="dataForm"
            style="padding:0 20px;"
            :rules="dialog.rules"
            :model="dialog.form"
            :disabled="dialog.disabled"
            label-width="80px"
          >
            <el-row>
              <el-form-item label="文件" prop="fileName">
                <el-input
                  v-model="dialog.form.fileName"
                  style="width:calc(100% - 100px)"
                  :maxlength="100"
                  disabled
                />
                <upload ref="upload" @on-success="uploadSuccess" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="题名" prop="subject">
                <el-input v-model="dialog.form.subject" clearable :maxlength="100" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="主题词" prop="keyWords">
                <el-input v-model="dialog.form.keyWords" clearable :maxlength="50" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="发文日期" prop="pubDate">
                  <el-date-picker v-model="dialog.form.pubDate" value-format="yyyy-MM-dd" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="文号" prop="docCode">
                  <el-input v-model="dialog.form.docCode" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="部门" prop="deptId">
                  <select-tree
                    v-model="dialog.form.deptId"
                    :options="depts"
                    :props="{ label: 'label', value: 'id', parent: 'parentId', children: 'children' }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="责任者" prop="personLiable">
                  <el-input v-model="dialog.form.personLiable" clearable :maxlength="30" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="密级" prop="scyCl">
                  <el-select v-model="dialog.form.scyCl" clearable>
                    <el-option v-for="item in secrets" :key="item.id" :label="item.dicKey" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="有效" prop="validFlag">
                  <el-switch v-model="dialog.form.validFlag" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </base-dialog>
  </div>
</template>
<script>
import { parseTime } from '@/utils';
import {
  getListPage,
  updateData,
  deleteData,
  getListTree,
  getListByTypeCode
} from '@/api/jjxt/tech-regulation';
import { isPdf } from '@/utils/validate';
import { downloadFile } from '@/utils/public';
import { getToken } from '@/utils/auth';
import Download from './components/Download';
import Upload from './components/Upload';
import { tableMixin } from '@/utils/public';

import TopNavigationBar from '@/views/jjxt/components/TopNavigationBar';

export default {
  name: 'DscTechRegulation',
  components: {
    TopNavigationBar,
    Download,
    Upload
  },
  mixins: [tableMixin],
  data() {
    return {
      listQuery: {
        page: 1,
        size: 20,
        organization: '',
        deptId: ''
      },
      filterData: {
        deptId: {
          key: 'deptId',
          type: 'selectTree',
          title: '部门',
          placeholder: '所有部门',
          options: [],
          props: {
            label: 'label',
            value: 'id',
            parent: 'parentId',
            children: 'children'
          }
        },
        pubDate: {
          key: 'pubDate',
          type: 'date',
          dateType: 'year',
          valueFormat: 'yyyy',
          placeholder: '发布年份'
        },
        validFlag: {
          key: 'validFlag',
          type: 'select',
          placeholder: '是否有效',
          options: [{ label: '有效', value: 1 }, { label: '无效', value: 0 }]
        },
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '题名、主题词'
        }
      },
      height: 0,
      listLoading: true,
      tableData: [],
      total: 0,
      dialog: {
        title: '',
        visible: false,
        disabled: false,
        loading: false,
        form: {},
        rules: {
          fileName: { required: true, message: '请选择', trigger: 'change' },
          subject: { required: true, message: '请输入', trigger: 'blur' },
          keyWords: { required: true, message: '请输入', trigger: 'blur' },
          pubDate: { required: true, message: '请选择', trigger: 'change' },
          docCode: { required: true, message: '请输入', trigger: 'blur' },
          deptId: { required: true, message: '请选择', trigger: 'blur' },
          personLiable: { required: true, message: '请输入', trigger: 'blur' },
          scyCl: { required: true, message: '请选择', trigger: 'change' }
        },
        fileList: []
      },
      currentRow: [],
      organizations: [],
      depts: [],
      secrets: [],
      parseTime: parseTime

      // // 表格数组
      // tableData: {
      //   list: [],
      //   total: 0
      // },

      // // baseTable组件配置
      // baseTableOption: {
      //   columns: [
      //     { prop: 'title', label: '标题', width: '250px' },
      //     { prop: 'year', label: '年份' },
      //     { prop: 'fileNo', label: '文件号' },
      //     { prop: 'dictSpecialtyName', label: '专业' },
      //     { prop: 'itemName', label: '规章类型', width: '200px' },
      //     { prop: 'shortName', label: '上传部门' },
      //     { prop: 'createDatetime', label: '上传时间' },
      //     { prop: 'ruleState', label: '状态' },
      //     { prop: 'disabledDate', label: '失效时间', formatter: (row) => row.disabledDate && row.ruleState === '失效' ? row.disabledDate : '' }
      //   ],
      //   showIndex: true,
      //   showSelection: false,
      //   showOperation: true,
      //   showFilterColumn: true,
      //   operatonWidth: '100px',
      //   defaultOperations: [],
      //   hasAuth: false,
      //   rowShowColor: { name: 'name', value: 0 }
      // }
    };
  },
  created() {
    this.getListPage();
    this.getList();
  },
  methods: {
    getList() {
      getListByTypeCode({ typeCode: this.publicConfig['023'] }).then(
        response => {
          this.organizations = response.data;
        }
      );
      getListByTypeCode({ typeCode: this.publicConfig['024'] }).then(
        response => {
          this.secrets = response.data;
        }
      );
      getListTree().then(response => {
        this.depts = response.data;
        this.filterData['deptId'].options = response.data;
      });
    },
    chooseOrganization(data) {
      if (data.id === this.listQuery.organization) return;
      this.listQuery.organization = this.dialog.form.organization = data.id;
      this.search();
    },
    getListPage() {
      this.listLoading = true;
      getListPage(this.listQuery)
        .then(response => {
          this.tableData = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(_ => {
          this.listLoading = false;
        });
    },
    search() {
      this.listQuery.page = 1;
      this.getListPage();
    },
    /** 查看 */
    view(row) {
      this.currentRow = [row];
      this.currentRow[0].pubDate = parseTime(
        this.currentRow[0].pubDate,
        '{y}-{m}-{d}'
      );
      const dialog = {
        title: '查看',
        visible: true,
        disabled: true,
        loading: false,
        form: row
      };
      this.dialog = Object.assign(this.dialog, dialog);
    },
    /** 添加 */
    addForm() {
      const dialog = {
        title: '添加',
        visible: true,
        disabled: false,
        loading: false,
        form: {
          organization: this.listQuery.organization,
          status: 1,
          delFlag: 0,
          validFlag: 1
        }
      };
      this.dialog = Object.assign(this.dialog, dialog);
    },
    /** 编辑 */
    updateForm(row, index) {
      this.currentRow = [row];
      this.currentRow[0].pubDate = parseTime(
        this.currentRow[0].pubDate,
        '{y}-{m}-{d}'
      );
      const dialog = {
        title: '编辑',
        visible: true,
        disabled: false,
        loading: false,
        form: JSON.parse(JSON.stringify(row))
      };
      this.dialog = Object.assign(this.dialog, dialog);
    },
    /** 添加或编辑接口 */
    updateData() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (!this.dialog.form.organization) {
            this.notifiyError('请选择发文机构!', '验证出错');
            return;
          }
          this.dialog.loading = true;
          updateData(this.dialog.form)
            .then(response => {
              this.dialog.visible = false;
              this.dialog.loading = false;
              this.currentRow = [response.data];
              if (this.dialog.title === '添加') {
                this.tableData.unshift(this.currentRow[0]);
                this.total++;
              } else {
                const index = this.tableData.findIndex(
                  item => item.id === this.currentRow[0].id
                );
                this.tableData.splice(index, 1, JSON.parse(JSON.stringify(this.currentRow[0])));
                this.$forceUpdate();
              }
              this.notifiySuccess('保存成功');
            })
            .catch(_ => {
              this.dialog.loading = false;
            });
        }
      });
    },
    deleteData(row, index) {
      this.confirmBox('确定删除?')
        .then(() => {
          deleteData(row.id).then(response => {
            this.notifiySuccess('删除成功!');
            this.tableData.splice(index, 1);
            this.total--;
          });
        })
        .catch(() => {});
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },
    uploadSuccess(response, file) {
      this.$set(this.dialog.form, 'fileName', file.name);
      this.$set(
        this.dialog.form,
        'subject',
        file.name.slice(0, file.name.lastIndexOf('.'))
      );
      this.$set(this.dialog.form, 'filePath', response.data);
    },
    beforeCloseDialog() {
      // this.$refs.dataForm.clearValidate()
      this.$refs.upload.uploadAbort();
    },
    // 预览pdf
    viewFile(row) {
      if (isPdf(row.filePath)) {
        window.open(`${this.publicPath}/pdf/web/viewer.html?file=${encodeURIComponent(this.getUrl(row))}`, '附件预览');
      } else {
        downloadFile({ url: row.filePath, fileName: row.fileName }).then(_ => {});
      }
    },
    getUrl(row) {
      return (
        process.env.VUE_APP_BASE_API +
        '/dfile/file/download?fileUrl=' +
        row.filePath +
        '&access_token=' +
        getToken()
      );
    }
  }
};
</script>
<style lang="scss">
.tech-regulation-dialog__left{
  margin-left: 20px;
}
.view-file{
  cursor: pointer;
  &:hover{
    color: #409EFF;
    text-decoration: underline;
  }
}
</style>
<style lang="scss" scoped>
::v-deep .el-range-separator {
  width: 25px !important;
}

.rules-regulations-management-style {
  background-color: #f1f4fb;
  height: 100%;
}

#background {
  background-size: 100% 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: -1;
}

.rules-regulations-of-power-supply-style {
  background-color: #ffffff;
  height: calc(100vh - 130px);
  margin: 30px;
  padding: 0;
  .top-operation {
    margin-left: 30px;
    padding-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
    .operation-input {
      width: 150px;
      margin-right: 10px;
    }
    .operation-select {
      width: 150px;
      margin-right: 10px;
    }
    .refresh-btn {
      background-color: #3dbed5;
      border: 1px solid #3dbed5;
    }
    .refresh-btn:hover {
      background-color: #73cddd;
      border: 1px solid #73cddd;
    }
  }
  .title {
    position: relative;
    padding: 30px 50px 22px 50px;
    font-size: 24px;
    color: #323232;
    &:after {
      content: '';
      position: absolute;
      left: 28px;
      top: 30px;
      width: 7px;
      height: 26px;
      background-color: #379df9;
      border-radius: 4px;
    }
  }

  .table-style {
    padding: 0 28px 20px 28px;
    background-color: #ffffff;
  }
  .page-box {
    padding: 0 28px 10px 28px;
    background-color: #ffffff;
  }

  // 内容区域
  .rules-content {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 0px 0px 0px 30px;
    .rules-content-right {
      flex: 1;
      .table-style {
        height: calc(100% - 120px);
      }
    }
  }
}
</style>

